#include "node.h"

Node *node_alloc_list(size_t size)
{
    Node *p;
    Node *q;
    for(size_t i = 0; i < size; ++i)
    {
        p = malloc(sizeof(Node));
        *p = (Node) {0};
        if(i == 0)
            q = p;
        else
            p->next = q;
        q = p;
    }
    return p;
}

void node_fill_list(Node *head, char *names[], int *nums, size_t list_size)
{
    int max_size = MIN(list_size, MIN(sizeof(nums), sizeof(names)));
    Node *p = head;
    for(int i = 0; i < max_size; ++i, p = p->next)
    {
        p->id = nums[i];
        p->text = names[i];
    }
}

Node *node_alloc_and_fill_list(size_t size, char *names[], int *nums)
{
    Node *p = node_alloc_list(size);
    node_fill_list(p, names, nums, size);
    return p;
}

Node *node_load_list_from_file(const char *fpath)
{
    errno = 0;
    FILE *f = fopen(fpath, "r");
    if(!f)
    {
        fprintf(stderr, "ERROR: could not open file %s\n: %s\n", fpath, strerror(errno));
        exit(1);
    }
    char **names = malloc(sizeof(char **));     //free
    int *nums = malloc(sizeof(int *));          //free

    char buffer[BUF_SIZE] = {0};
    char *str;
    for(int i = 1; f != EOF; ++i)
    {
        int n_leidos = getline(buffer, BUF_SIZE, f);
        if(n_leidos < 0)
        {
            fprintf(stderr, "ERROR: could not read from file %s: %s\n", fpath, strerror(errno));
            exit(1);
        }
        *(buffer + strlen(buffer) - 1) = '\0';
        str = strtok(buffer, ' ');
        if(i > sizeof(nums))
        {
            nums = realloc(nums, sizeof(char **) * (i + 1));
            names = realloc(names, sizeof(int *) * (i + 1));
        }
        nums[i - 1] = atol(str);
        names[i - 1] = buffer;
        free(str);
        free(buffer);
    }

}
void node_print_list(Node *head)
{
    for(Node *i = head; i; i = i->next)
        printf("%d: %s\n", i->id, i->text);
}

void node_free_list(Node *head)
{
    Node *p;
    Node *k;
    for(p = head; p; p = k)
    {
        k = p->next;
        free(p);
    }
}
